package utility;

import java.io.*;
import java.util.logging.*;

import javax.xml.stream.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

import com.siemens.ct.exi.*;
import com.siemens.ct.exi.api.sax.*;
import com.siemens.ct.exi.api.stream.*;
import com.siemens.ct.exi.exceptions.*;
import com.siemens.ct.exi.grammars.*;
import com.siemens.ct.exi.helpers.*;
import com.thoughtworks.xstream.io.*;
import com.thoughtworks.xstream.io.xml.*;

public class ExiWriter implements HierarchicalStreamWriter {
   private SaxWriter sax;
   private DomWriter dom;
   private static Logger log = Logger.getGlobal();
   
   public ExiWriter (OutputStream out) throws EXIException, IOException, SAXException{
      this (null, out);
   }
   
   public ExiWriter (EXIFactory factory, OutputStream out) throws EXIException, IOException, SAXException {
      
      // Create the EXI writer
      EXIResult result = new EXIResult(factory);
      
      // Set the writer to output to the indicated output stream
      result.setOutputStream(out);
      
      // Get the SAX handler
      ContentHandler handler = result.getHandler();
      
      // Build the SAX writer and set it to output to the EXI writer
      sax = new SaxWriter();
      sax.setContentHandler(new ForcedNamespaceSaxIntermediary(handler, "xsi", "http://www.w3.org/2001/XMLSchema-instance"));
   }

   @Override
   public void startNode(String name) {
//      System.out.println("ExiWriter.startNode (" + name + ")");
      sax.startNode(name);
   }

   @Override
   public void addAttribute(String name, String value) {
//      System.out.println("ExiWriter.addAttribute (" + name + ", " + value + ")");
      sax.addAttribute(name, value);
   }

   @Override
   public void setValue(String text) {
//      System.out.println("ExiWriter.setValue (" + text + ")");
      sax.setValue(text);
   }

   @Override
   public void endNode() {
//      System.out.println("ExiWriter.endNode()");
      sax.endNode();
   }

   @Override
   public void flush() {
//      System.out.println("ExiWriter.flush()");
      sax.flush();
   }

   @Override
   public void close() {
//      System.out.println("ExiWriter.close()");
      sax.close();
   }

   @Override
   public HierarchicalStreamWriter underlyingWriter() {
//      System.out.println("ExiWriter.underlyingWriter()");
      return sax.underlyingWriter();
   }     
}
